define(["jquery"],function($){
  
  try{
    
    var SOCKET_URL = "ws://gcc.cixunkeji.com/yoyo/ws/common";
    
    var onmessage = function(ev){
      var obj = null;
      try{
        obj=JSON.parse(ev.data);
        if(obj._socket_id&&SocketUtils._activities[obj._socket_id]&&SocketUtils._activities[obj._socket_id].onSuccess){
          SocketUtils._activities[obj._socket_id].onSuccess(obj.data);
        }
        SocketUtils._activities[obj._socket_id]=undefined;
      }catch(e){
        console.error(e);
        console.error(ev.data);
      }
    };

    var onopen = function(ev){
      try{
      SocketUtils._socket_enable=true;
      while(SocketUtils._waiting_activities.length>0){
        var param = SocketUtils._waiting_activities.pop();
        var param_str = JSON.stringify(param);
        try{
          this.send(param_str);
          SocketUtils._activities[param._socket_id]=param;
        }catch(e){
          console.log(e);
        }
      }
      }catch(e){
        console.log(e);
      }
      
    };
    var onerror = function(ev){
      SocketUtils._socket_enable=false;
      console.log(ev);
    }
    

    var onclose=function(ev){
      SocketUtils._socket_enable=false;
    };
    
    /*
     * socket工具
     */
    function SocketUtils(bizId){
      this.bizId=bizId;
    }
    
    
    SocketUtils._socket_enable=false;
    SocketUtils._socket=undefined;
      
      
      function init_socket(){
        if(SocketUtils._socket){
          SocketUtils._socket.close();
        }
        SocketUtils._socket=new WebSocket(SOCKET_URL);
        SocketUtils._socket.onmessage=onmessage;
        SocketUtils._socket.onopen=onopen;
        SocketUtils._socket.onerror=onerror;
        SocketUtils._socket.onclose=onclose;
      }
      
    SocketUtils._activities={};
    SocketUtils._waiting_activities=[];
    
    SocketUtils.prototype.send=function(param, onSuccess){
      try{
        param.onSuccess=onSuccess;
        param.business=this.bizId;
        param._socket_id=uuid();
        param.sendTm=new Date().getTime();
        
        if(!SocketUtils._socket){
          init_socket();
        }
        
        if(SocketUtils._socket_enable){
          var param_str = JSON.stringify(param);
          SocketUtils._activities[param._socket_id]=param;
          SocketUtils._socket.send(param_str);
        }else{
          SocketUtils._waiting_activities.push(param);
        }
      }catch(e){
        SocketUtils._waiting_activities.push(param);
        SocketUtils._activities[param._socket_id]=undefined;
        console.log(e);
      }
    }
    
    window.SocketUtils=SocketUtils;
    return SocketUtils;
    

  }catch(e){
    console.log(e);
  }
  
  
});